<template>
  <el-upload
    class="avatar-uploader"
    action=""
    :show-file-list="false"
    :http-request="httpUpload"
    :multiple="multiple"
    :accept="accept"
  >
    <img
      v-if="oldFileUrl || imageUrl"
      :src="oldFileUrl || imageUrl"
      class="avatar"
      :style="{ 'max-height': iconHeight + 'px' }"
    />
    <div
      v-else
      class="avatar-uploader-icon flex-xyc"
      :style="{ width: iconWidth + 'px', height: iconHeight + 'px' }"
    >
      <el-icon><Plus /></el-icon>
    </div>
  </el-upload>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

import type { UploadProps, UploadRequestOptions } from 'element-plus'
import { fileBase64, httpRequest } from '@/api/common'
import axios from 'axios'

const imageUrl = ref('')
const props = withDefaults(
  defineProps<{
    iconWidth?: string
    iconHeight?: string
    modeValue: string
    uploadUrl?: string
    multiple?: boolean
    accept?: string
    oldFileUrl?: string
  }>(),
  {
    iconWidth: '100',
    iconHeight: '100',
    modeValue: '',
    uploadUrl: '',
    multiple: false,
  },
)
const $emit = defineEmits<{
  uploadRespLoaded(value: string): void
}>()

const httpUpload = async (options: UploadRequestOptions) => {
  if (props.uploadUrl) {
    ElMessage.warning('上传中')
    console.log(options.file, 9999)
    const file = await fileBase64(options.file)
    imageUrl.value = file

    const formData = new FormData()
    formData.append('file', options.file)

    let resp = await axios.request({
      url: props.uploadUrl,
      method: 'post',
      headers: { 'Content-Type': 'multipart/form-data' },
      data: formData,
    })
    $emit('uploadRespLoaded', resp)
    ElMessage.success('上传成功')
    console.log(resp, 7777)
  }
}
</script>

<style scoped lang="scss">
.avatar-uploader-icon {
  color: #8c939d;
  border: 1px dashed var(--el-border-color);
}
</style>
